const data = require('./user_1.json')

const fs = require('fs')

const express = require('express')
const router = express.Router()


var user = ((req, res) => {
    res.json(data);
});

//搜索
var search = ((req, res) => {
    var search = data.find(item => item.name == req.body.name)
    res.json(search)
});


//删除
var del = ((req, res) => {

    var del = data.findIndex(item => item.id == req.body.id)
    sp = JSON.parse(fs.readFileSync('./user_1.json').toString())
    res.json(del)
    sp.splice(del, 1)
    fs.writeFileSync('./user_1.json', JSON.stringify(sp))
})


//添加
var add = ((req, res) => {
    var user = fs.readFileSync("./user_1.json")
    var obj = JSON.parse(user.toString())
    console.log(obj.length);
    obj.push({
        id: obj.length + 1,
        StudentIDnumber: req.body.StudentIDnumber,
        name: req.body.name,
        Classnumber: req.body.Classnumber,
        Mathematics: req.body.Mathematics,
        English: req.body.English,
        language: req.body.language,
        semester: req.body.semester
    })
    fs.writeFileSync('./user_1.json', JSON.stringify(obj))
})


//修改
var modify = ((req, res) => {
    var modify = data.findIndex(item => item.id == req.body.id)
    sp = JSON.parse(fs.readFileSync('./user_1.json').toString())
    res.json(modify)
    sp.splice(modify, 1, {
        StudentIDnumber: req.body.StudentIDnumber,
        name: req.body.name,
        Classnumber: req.body.Classnumber,
        Mathematics: req.body.Mathematics,
        English: req.body.English,
        language: req.body.language,
        semester: req.body.semester
    })
    fs.writeFileSync('./user_1.json', JSON.stringify(sp))
})


router.get('/list', user)
router.post('/search', search)
router.post('/add', add)
router.post('/del', del)
router.post('/modify', modify)

module.exports = router